package com.xhwl.data.aop;

import com.google.common.base.Joiner;
import com.xhwl.common.exception.DataException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: zhuyitao
 * @Description:
 * @Date: 2022/7/7
 */
@Aspect
@Component
public class ParameterValidAop {
    /**
     * 对切面进行字段验证
     *
     * @param joinPoint 切点
     * @return Object
     * @throws Throwable
     */
    @Around("execution(* com.xhwl.data.controller.*Controller.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        List<String> errorList = new ArrayList<>();
        if (args != null) {
            Arrays.stream(args)
                    .forEach(arg -> {
                        if (arg instanceof BindingResult) {
                            BindingResult result = (BindingResult) arg;
                            if (result.hasErrors()) {
                                result.getAllErrors()
                                        .forEach(err -> errorList.add(err.getDefaultMessage()));
                                throw new DataException((Joiner.on(" || ").join(errorList)));
                            }
                        }
                    });
        }
        return joinPoint.proceed();
    }
}
